package com.sto.stoapp.db.manager;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.entity.BaseEntity;
import com.sto.stoapp.entity.LoginInfoEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 登陆信息管理类
 * 
 * @author mgf
 * 
 */
public class LoginInfoManager extends StoDataBase {

	private static LoginInfoManager loginInfoManager;

	private static final String SQL_QUERY_BY_USER = "select * from "
			+ LOGIN_INFO_TABLE + " where " + JOB_NUMBER + " =? and "
			+ PASSWORD_INFO + " =? ";

	// 根据用户编号搜索某一条数据
	public static final String SQL_QUERY_ONLY = "select * from "
			+ LOGIN_INFO_TABLE + " where " + JOB_NUMBER + " = ? ";

	public static final String DELECT_BY_JOB_NUMBER_AND_PASSWORD = "delect from "
			+ LOGIN_INFO_TABLE
			+ " where "
			+ JOB_NUMBER
			+ " =? and "
			+ PASSWORD_INFO + " =? ";
	
	// 查询所有数据(目前该表永远只有一条数据)
    public static final String SQL_QUERY_BY_SITE_CODE = "select * from "
            + LOGIN_INFO_TABLE + " where " + LOGIN_SITE_NAME + " = ? ";

	private LoginInfoManager(Context context) {
		super(context);
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static LoginInfoManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (loginInfoManager == null) {
				loginInfoManager = new LoginInfoManager(context);
			}
			return loginInfoManager;
		}
	}

	/**
	 * 插入一条数据
	 * 
	 * @param entity
	 * @return
	 */
	public boolean insert(BaseEntity entity) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			LoginInfoEntity loginEntity = null;
			if (entity instanceof LoginInfoEntity) {
				loginEntity = (LoginInfoEntity) entity;
			} else {
				return false;
			}
			try {
				ContentValues values = new ContentValues();
				values.put(JOB_NUMBER, loginEntity.getJobNumber());
				values.put(PASSWORD_INFO, loginEntity.getPwdInfo());
				values.put(LOGIN_ATTRIBUTE, loginEntity.getLoginAttribute());
				values.put(LOGIN_SITE_NAME, loginEntity.getSiteName());
				values.put(LOGIN_NAME, loginEntity.getLoginName());
				values.put(TELPHONE_NUMBER, loginEntity.getTelphoneNumber());
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.insert(LOGIN_INFO_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条登陆信息", "成功");
				} else {
					Log.d("插入一条登陆信息", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}
	
	/**
     * 插入一条数据
     * 
     * @param entity
     * @return
     */
    public boolean insertOnly(BaseEntity entity) {
        synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
            long res = -1;
            LoginInfoEntity loginEntity = null;
            if (entity instanceof LoginInfoEntity) {
                loginEntity = (LoginInfoEntity) entity;
            } else {
                return false;
            }
            try {
                res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
                        .delete(LOGIN_INFO_TABLE, null, null);
                
                ContentValues values = new ContentValues();
                values.put(JOB_NUMBER, loginEntity.getJobNumber());
                values.put(PASSWORD_INFO, loginEntity.getPwdInfo());
                values.put(LOGIN_ATTRIBUTE, loginEntity.getLoginAttribute());
                values.put(LOGIN_SITE_NAME, loginEntity.getSiteName());
                values.put(LOGIN_NAME, loginEntity.getLoginName());
                values.put(TELPHONE_NUMBER, loginEntity.getTelphoneNumber());
                values.put(ORG_AIR_TYPE, loginEntity.orgAirType);
                values.put(ORG_TYPE, loginEntity.orgType);
                res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
                        .insert(LOGIN_INFO_TABLE, null, values);
                if (res > 0) {
                    Log.d("插入一条登陆信息", "成功");
                } else {
                    Log.d("插入一条登陆信息", "失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                ExceptionLog.writeLog("insert", e.getMessage());
            } finally {
                closeDb(UnifiedStaticType.WRITE_DATABASE);
            }
            return res > 0 ? true : false;
        }
    }

	public void delectByUserInfo(String number, String passWord) {
		getWritableDatabase().delete(LOGIN_INFO_TABLE,
				JOB_NUMBER + " =? and " + PASSWORD_INFO + " =? ",
				new String[] { number, passWord });
	}

	/**
	 * 根据工号、密码查询登陆信息
	 * 
	 * @param userInfo
	 * @param pwdInfo
	 * @return
	 */
	public LoginInfoEntity queryByUserInfo(String userInfo, String pwdInfo) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			LoginInfoEntity data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(
					SQL_QUERY_BY_USER, new String[] { userInfo, pwdInfo }));
			return data;
		}
	}

	/**
	 * 根据工号查询登陆信息
	 * 
	 * @author mgf
	 * @param jobNumber
	 *            用户编号
	 * @return 用户名称;""：没找到
	 */
	public LoginInfoEntity queryInfoByJob(String jobNumber) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			LoginInfoEntity data = getDataFromCursor(getSqliteDatabase(
					UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_ONLY,
					new String[] { jobNumber }));
			return data;
		}
	}
	
	public LoginInfoEntity queryInfoBySiteCode(String siteCode) {
        synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
            LoginInfoEntity data = getDataFromCursor(getSqliteDatabase(
                    UnifiedStaticType.READ_DATABASE).rawQuery(SQL_QUERY_BY_SITE_CODE,
                    new String[] {siteCode}));
            return data;
        }
    }
	

	/**
	 * 根据工号查询登陆名称
	 * 
	 * @author wxf
	 * @param jobNumber
	 *            用户编号
	 * @return 用户名称;""：没找到
	 */
	public String queryUserNameByJob(String jobNumber) {
		String userName = "";
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			Cursor c = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
					.rawQuery(SQL_QUERY_ONLY, new String[] { jobNumber });
			if (c != null) {
				if (c.moveToFirst()) {
					userName = c.getString(c.getColumnIndex(LOGIN_NAME));
				}

			}
			closeCursor(c);
			closeDb(UnifiedStaticType.READ_DATABASE);
			return userName;
		}
	}

	/**
	 * 根据工号查询登陆站点名称
	 * 
	 * @author wxf
	 * @param jobNumber
	 *            站点名称
	 * @return 用户名称;""：没找到
	 */
	public String querySiteNameByJob(String jobNumber) {
		String siteName = "";
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {

			Cursor c = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
					.rawQuery(SQL_QUERY_ONLY, new String[] { jobNumber });
			if (c != null) {
				if (c.moveToFirst()) {
					siteName = c.getString(c.getColumnIndex(LOGIN_SITE_NAME));
				}

			}
			closeCursor(c);
			closeDb(UnifiedStaticType.READ_DATABASE);
			return siteName;
		}
	}

	private LoginInfoEntity getDataFromCursor(final Cursor c) {
		LoginInfoEntity lstData = null;
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					lstData = getSingleData(c);
				} while (c.moveToNext());
			}
			closeCursor(c);
		}
		closeDb(UnifiedStaticType.READ_DATABASE);
		return lstData;
	}

	private LoginInfoEntity getSingleData(Cursor c) {
		LoginInfoEntity data = new LoginInfoEntity();
		data.setJobNumber(c.getString(c.getColumnIndex(JOB_NUMBER)));
		data.setPwdInfo(c.getString(c.getColumnIndex(PASSWORD_INFO)));
		data.setLoginAttribute(c.getString(c.getColumnIndex(LOGIN_ATTRIBUTE)));
		data.setSiteName(c.getString(c.getColumnIndex(LOGIN_SITE_NAME)));
		data.setLoginName(c.getString(c.getColumnIndex(LOGIN_NAME)));
		data.setTelphoneNumber(c.getString(c.getColumnIndex(TELPHONE_NUMBER)));
		data.orgAirType = c.getString(c.getColumnIndex(ORG_AIR_TYPE));
        data.orgType = c.getString(c.getColumnIndex(ORG_TYPE));
		return data;
	}

	/**
	 * 删除所有登陆信息表
	 * 
	 * @return
	 */
	public boolean deleteAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(LOGIN_INFO_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

}
